package apifm

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/blog/rpc/blogclient"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"

	"github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetCmsPageInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetCmsPageInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCmsPageInfoLogic {
	return &GetCmsPageInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetCmsPageInfoLogic) GetCmsPageInfo(
	req *types.GetCmsPageInfoReq,
	headers *[]*types.Header,
) (resp *types.CmsPageInfo, err error) {
	if req.Key == nil || len(strings.TrimSpace(*req.Key)) == 0 {
		return nil, resultx.NewErrCode(resultx.REUQEST_PARAM_ERROR)
	}

	var key string
	switch strings.TrimSpace(*req.Key) {
	case "tou":
		key = "terms of use"
	case "pp":
		key = "privacy policy"
	case "tc":
		key = "terms and conditions of integral system of members"
	default:
		key = "about us"
	}

	userId := jwt.GetUserId(l.ctx)

	return l.getCmsPageInfo(key, userId)
}

func (l *GetCmsPageInfoLogic) getCmsPageInfo(key string, userId uint64) (*types.CmsPageInfo, error) {
	preload := "blogPage:Id,Title,Slug"
	preload += ";blogPageDetail:ContentHtml"
	eagerLoad := "blogPage:blogPageDetail"
	filters := []string{
		"Slug,equalTo:" + key,
		"Status,equalTo:" + strconv.FormatInt(int64(globalkey.PostStatusPublish), 10),
	}
	var platformId uint32 = globalkey.ThirdPartyPlatformWechatMini

	res, err := l.svcCtx.BlogRpc.GetPageBySlug(l.ctx, &blogclient.BaseIdReq{
		Preload:    pointy.GetPointer(preload),
		EagerLoad:  pointy.GetPointer(eagerLoad),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(platformId),
	})
	if err != nil {
		logrus.Info(fmt.Sprintf("getCmsPageInfo GetPageBySlug err: %+v", err))
		return nil, err
	}

	return &types.CmsPageInfo{
		Id:      res.Id,
		Title:   res.Title,
		Slug:    res.Slug,
		Content: res.Content,
	}, nil
}
